import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:part_time_job_pro/common/index.dart';
import 'package:part_time_job_pro/pages/public/part/detail/state.dart';

class PartDetailLogic extends GetxController {
  final PartDetailState state = PartDetailState();

  final ScrollController scrollController = ScrollController();

  ///输入监听
  late TextEditingController signUpCountTextEditController;
  late TextEditingController salaryTextEditController;
  late TextEditingController mobileTextEditController;
  late TextEditingController contactTextEditController;
  late TextEditingController emailTextEditController;

  ///监听是否正在输入数据
  late FocusNode signUpCountFocusNode;
  late FocusNode salaryCountFocusNode;
  late FocusNode mobileFocusNode;
  late FocusNode contactFocusNode;
  late FocusNode emailFocusNode;

  @override
  void onInit() {
    super.onInit();
    salaryTextEditController = TextEditingController();
    signUpCountTextEditController = TextEditingController();
    contactTextEditController = TextEditingController();
    mobileTextEditController = TextEditingController();
    emailTextEditController = TextEditingController();

    emailFocusNode = FocusNode();
    contactFocusNode = FocusNode();
    mobileFocusNode = FocusNode();
    signUpCountFocusNode = FocusNode();
    salaryCountFocusNode = FocusNode();

    scrollController.addListener(() {
      double offset = scrollController.offset; // 当前滚动偏移量
      print('当前滚动位置: $offset');
      state.scrollBarThickness = 2.0;
      Future.delayed(
        const Duration(seconds: 1),
        () {
          state.scrollBarThickness = 0.0;
          update();
        },
      );
    });
  }

  @override
  void onReady() {
    state.jobData = Get.arguments;
    LogUtil.e(state.jobData, tag: "jobData");
    getJobSexReqList();
    getSalaryUnitList();
    getCashPeriodList();
    getWorkWelfareList();
    getPerWeekWorkDay();
    getWorkTimeLimitList();
    super.onReady();
  }

  @override
  void onClose() {
    salaryTextEditController.dispose();
    signUpCountTextEditController.dispose();
    contactTextEditController.dispose();
    mobileTextEditController.dispose();
    emailTextEditController.dispose();
    super.onClose();
  }

  //清空名称输入
  clearSignUpCount() {
    state.signUpCount = 0;
    signUpCountTextEditController.clear();
    signUpCountFocusNode.unfocus();
    update();
  }

  ///监听名称输入
  updateSignUpCount(String text) {
    LogUtil.e(text, tag: "text");
    if (text.isNotEmpty) {
      state.signUpCount = int.parse(text);
    }
    update();
  }

  //清空工资输入
  clearSalaryUpCount() {
    state.salary = 0.0;
    salaryTextEditController.clear();
    salaryCountFocusNode.unfocus();
    update();
  }

  ///监听工资输入
  updateSalaryCount(String text) {
    if (text.isNotEmpty) {
      state.salary = double.parse(text);
    } else {
      state.salary = 0.0;
    }
    update();
  }

  ///监听联系人输入
  updateContactName(String text) {
    state.contactName = text;
    update();
  }

  //清空账号输入
  clearContactName() {
    state.contactName = '';
    contactTextEditController.clear();
    contactFocusNode.unfocus();
    update();
  }

  ///监听电话输入
  updateTel(String text) {
    state.mobileText = text;
    update();
  }

  //清空电话输入
  clearTel() {
    state.mobileText = '';
    mobileTextEditController.clear();
    mobileFocusNode.unfocus();
    update();
  }

  ///监听email输入
  updateEmail(String text) {
    state.emailText = text;
    update();
  }

  //清空email输入
  clearEmail() {
    state.emailText = '';
    emailTextEditController.clear();
    emailFocusNode.unfocus();
    update();
  }

  ///是否接收咨询
  changeIsAcceptMobileCall() {
    state.isAcceptMobileCall = !state.isAcceptMobileCall;
    update();
  }

  //改变工作种类
  changeWorkType(int type) {
    state.workType = type;
    update();
  }

  //选择上班开始时间
  changeStartWorkTime(DateTime time) {
    //开始时间
    DateTime startTime = DateTime(1, 1, 1, time.hour, time.minute);
    state.startTime = startTime.toString().substring(11, 16).trim();
    //结束时间 +15分钟
    DateTime endTime = startTime.add(const Duration(minutes: 15));
    state.endTime = endTime.toString().substring(11, 16).trim();
    state.initStartTime = startTime;
    state.initEndTime = endTime;
    LogUtil.e(state.startTime, tag: "startTime");
    LogUtil.e(state.endTime, tag: "endTime");
    Future.delayed(const Duration(milliseconds: 500), () {
      update();
    });
  }

  //选择上班结束时间
  changeEndWorkTime(DateTime time) {
    LogUtil.e(time, tag: "time");
    //结束时间
    DateTime oldTime = state.initEndTime;
    DateTime newTime = DateTime(1, 1, 1, time.hour, time.minute);
    LogUtil.e(oldTime, tag: "oldTime");
    LogUtil.e(newTime, tag: "newTime");
    LogUtil.e(state.initStartTime, tag: "state.initStartTime");
    if (newTime.isAtSameMomentAs(state.initStartTime) || newTime.isBefore(state.initStartTime)) {
      Future.delayed(const Duration(milliseconds: 500), () {
        state.initEndTime = oldTime;
        state.endTime = oldTime.toString().substring(11, 16).trim();
        update();
      });
    } else {
      Future.delayed(const Duration(milliseconds: 500), () {
        state.initEndTime = newTime;
        state.endTime = newTime.toString().substring(11, 16).trim();
        update();
      });
    }
    LogUtil.e(state.endTime, tag: "endTime");
  }

  //提交上班时间
  submitWorkTime() {
    String workTime = "${state.startTime}-${state.endTime}";
    if (!state.workTimeList.contains(workTime)) {
      state.workTimeList.add(workTime);
    }
    LogUtil.e(state.workTimeList, tag: "state.workTimeList");
    Future.delayed(const Duration(milliseconds: 500), () {
      //清理数据
      initTimeSelect();
    });
    Get.back();
  }

  //删除上班时间
  removerWorkTime(time) {
    if (state.workTimeList.contains(time)) {
      state.workTimeList.remove(time);
    }
    update();
  }

  //关闭上班时间选择
  closeTimeSelect() {
    Future.delayed(const Duration(milliseconds: 500), () {
      //清理数据
      initTimeSelect();
    });
    Get.back();
  }

  //删除工作日期
  removerWorkDate(date) {
    if (state.workDateList.contains(date)) {
      state.workDateList.remove(date);
    }
    update();
  }

  //关闭工作日期选择
  closeDateSelect() {
    Future.delayed(const Duration(milliseconds: 500), () {
      //清理数据
      initDateSelect();
    });
    Get.back();
  }

  //提交工作时间
  submitWorkDate(List<DateTime>? results) {
    LogUtil.e(results, tag: "results====");
    if (results != null) {
      if (results.length > 1) {
        state.startDate = results[0].toString().substring(0, 10);
        state.endDate = results[1].toString().substring(0, 10);
      } else {
        state.startDate = results[0].toString().substring(0, 10);
        state.endDate = results[0].toString().substring(0, 10);
      }
      String workDate = "${state.startDate.trim()}#${state.endDate.trim()}";
      if (!state.workDateList.contains(workDate)) {
        state.workDateList.add(workDate);
      }
      LogUtil.e(state.workDateList, tag: "state.workDateList");
      update();
    }
  }

  //初始化日期
  initDateSelect() {
    state.initDate = DateUtils.dateOnly(DateTime.now());
    state.startDate = "";
    state.endDate = "";
    state.workDateList = [];
    update();
  }

  //初始化时间
  initTimeSelect() {
    state.startTime = "08:00";
    state.endTime = "08:15";
    state.initStartTime =
        DateTime(1, 1, 1, int.parse(state.startTime.split(":")[0]), int.parse(state.startTime.split(":")[1]));
    state.initEndTime =
        DateTime(1, 1, 1, int.parse(state.endTime.split(":")[0]), int.parse(state.endTime.split(":")[1]));
    update();
  }

  //获取工资单位
  getJobSexReqList() {
    JobApi().getDictDataList((data) {
      if (data is List<SysDictData>) {
        state.selectUserSexList = data;
        LogUtil.e(state.selectUserSexList, tag: "性别要求");
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, workSexReq);
  }

  //获取工资单位
  getSalaryUnitList() {
    JobApi().getDictDataList((data) {
      if (data is List<SysDictData>) {
        state.salaryUnitList = data;
        LogUtil.e(state.salaryUnitList, tag: "工资单位数据");
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, salaryUnit);
  }

  //获取结算周期
  getCashPeriodList() {
    JobApi().getDictDataList((data) {
      if (data is List<SysDictData>) {
        state.cashPeriodList = data;
        LogUtil.e(state.cashPeriodList, tag: "结算周期数据");
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, cashPeriod);
  }

  //获取工作福利数据
  getWorkWelfareList() {
    JobApi().getDictDataList((data) {
      if (data is List<SysDictData>) {
        //兼职不需要全勤选项所以要排除
        for (var item in data) {
          if (item.dictLabel!=null && !item.dictLabel!.contains("全勤奖")) {
            state.workWelfareList.add(item);
          }
        }
        LogUtil.e(state.workWelfareList, tag: "工作福利数据");
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, workWelfare);
  }

  //获取上班时间要求
  getWorkTimeLimitList() {
    JobApi().getDictDataList((data) {
      if (data is List<SysDictData>) {
        state.workTimeLimitList = data;
        LogUtil.e(state.workTimeLimitList, tag: "时间要求数据");
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, workTimeLimit);
  }

  //获取每周工作天数
  getPerWeekWorkDay() {
    JobApi().getDictDataList((data) {
      if (data is List<SysDictData>) {
        state.weekWorkDayList = data;
        LogUtil.e(state.weekWorkDayList, tag: "每周至少工作数据");
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, weekWorkDay);
  }

  //获取已经选择的工作福利
  getSelectWelfare() {
    List<String> welfarelist = [];
    for (var item in state.workWelfareList) {
      if (item.checked) {
        welfarelist.add(item.dictValue!);
      }
    }
    return welfarelist.toList();
  }

  //提取性别
  findDictValueByLabel(List<SysDictData> dictDataList, String dictLabel) {
    String dictValue = "";
    for (var item in dictDataList) {
      if (item.dictLabel == dictLabel) {
        dictValue = item.dictValue!;
      }
    }
    LogUtil.e(dictValue, tag: "提取到的【$dictLabel】对应的value为====>");
    return dictValue;
  }

  submitPartTimeJob() {
    //封装数据
    if (state.signUpCount == 0) {
      EasyLoading.showToast("请输入报名人数!");
      return;
    }
    state.jobData["applyNum"] = state.signUpCount;

    if (state.selectUserSex.isEmpty) {
      EasyLoading.showToast("请选择性别要求!");
      return;
    }
    //处理性别
    state.jobData["sexReq"] = findDictValueByLabel(state.selectUserSexList, state.selectUserSex);

    if (state.salary <= 0.0) {
      EasyLoading.showToast("请输入基本工资!");
      return;
    }
    state.jobData["salary"] = state.salary;

    if (state.selectSalaryUnit.isEmpty) {
      EasyLoading.showToast("请选择工资单位!");
      return;
    }
    //处理工资单位
    state.jobData["salaryUnitName"] = state.selectSalaryUnit;
    state.jobData["salaryUnit"] = findDictValueByLabel(state.salaryUnitList, state.selectSalaryUnit);

    if (state.selectCashPeriod.isEmpty) {
      EasyLoading.showToast("请选择结算周期!");
      return;
    }

    if (state.selectCashPeriod.isEmpty) {
      EasyLoading.showToast("请选择结算周期!");
      return;
    }
    //处理结算周期
    state.jobData["cashPeriod"] = findDictValueByLabel(state.cashPeriodList, state.selectCashPeriod);

    state.selectWorkWelfare = getSelectWelfare().toString();
    LogUtil.e(state.selectWorkWelfare, tag: "state.selectWorkWelfare");
    if (state.selectWorkWelfare.isNotEmpty) {
      state.jobData["jobWelfare"] = state.selectWorkWelfare;
    }
    //工作种类
    state.jobData["workSpecies"] = state.workType;
    if (state.workType == 0) {
      if (state.workDateList.isEmpty) {
        EasyLoading.showToast("请选择工作日期!");
        return;
      }
      state.jobData["workDate"] = state.workDateList.toString();
    } else {
      if (state.selectWorkTimeLimit.isEmpty) {
        EasyLoading.showToast("请选择时间要求!");
        return;
      }
      state.jobData["timeRequire"] = findDictValueByLabel(state.workTimeLimitList, state.selectWorkTimeLimit);

      //每周上班天数
      if (state.selectWeekWorkDay.isEmpty) {
        EasyLoading.showToast("请选择每周上班天数!");
        return;
      }
      state.jobData["weeklyWorkDay"] = findDictValueByLabel(state.weekWorkDayList, state.selectWeekWorkDay);
    }

    if (state.workTimeList.isEmpty) {
      EasyLoading.showToast("请选择上班时间!");
      return;
    }
    state.jobData["workTime"] = state.workTimeList.toString();

    if (state.emailText.isEmpty) {
      EasyLoading.showToast("请输入联系人电子邮箱!");
      return;
    }
    state.jobData["email"] = state.emailText;

    if (state.contactName.isEmpty) {
      EasyLoading.showToast("请输入联系人电话号码!");
      return;
    }
    state.jobData["contactPerson"] = state.contactName;

    if (state.mobileText.isEmpty) {
      EasyLoading.showToast("请输入联系人电话号码!");
      return;
    }

    state.jobData["mobile"] = state.mobileText;
    state.jobData["offerMobile"] = state.isAcceptMobileCall ? "1" : "0";

    //获取用户ID
    String userId = StorageService.to.getString(STORAGE_USER_ID_KEY);
    if (CommonUtil.isNotEmpty(userId)) {
      state.jobData["userId"] = userId;
    }

    //获取用户账号
    String loginAccount = StorageService.to.getString(STORAGE_USER_ACCOUNT_KEY);
    if (CommonUtil.isNotEmpty(loginAccount)) {
      state.jobData["userName"] = loginAccount;
    }

    JobApi().submitPartTimeJob((data) {
      int resultCode = data[ResponesCode.codeTag];
      if (resultCode == ResponesCode.successCode) {
        var resultData = data[ResponesCode.dataTag];
        if (resultData == "1") {
          EasyLoading.showToast("恭喜您，职位发布成功!");
          //进入首页
          Future.delayed(const Duration(seconds: 1)).whenComplete(() {
            Get.offAndToNamed(AppRoutes.homePage);
          });
        } else {
          EasyLoading.showToast("很抱歉，职位发布失败!");
        }
      } else {
        state.errorMsg = data;
        EasyLoading.showError(data["msg"]);
      }
      update();
    }, state.jobData);
  }
}
